﻿using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Xml;

namespace Tools.Modules.Navigations.ViewModels
{
    public class JsonToXmlViewModel : BindableBase,INavigationAware
    {
        private string _json;
        public string Json
        {
            get => _json;
            set=>SetProperty(ref _json, value);
        }
        private string _xml;
        public string Xml
        {
            get => _xml;
            set=>SetProperty(ref _xml, value);
        }
        public DelegateCommand JsonToXmlCommand { get; private set; }
        public DelegateCommand XmlToJsonCommand { get; private set; }
        public JsonToXmlViewModel()
        {
            JsonToXmlCommand = new DelegateCommand(() =>
            {
                try 
                {
                    XmlDocument xml = JsonConvert.DeserializeXmlNode(Json, "root", false);
                    Xml = xml.DocumentElement.InnerXml;
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });
            XmlToJsonCommand = new DelegateCommand(() =>
            {
                try
                {
                    XmlDocument xml = new XmlDocument();
                    var node = xml.CreateNode(XmlNodeType.Element, "root", "");
                    node.InnerXml = Xml;
                    xml.AppendChild(node);
                    xml.PreserveWhitespace = false;
                    Json = JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented, true);
                }catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            });
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
        }
    }
}
